Euler Problem 17

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.


In [1]:
def spellout(n):
    small = [3, 3, 5, 4, 4, 3, 5, 5, 4] # 1 - 9
    teens = [6, 6, 8, 8, 7, 7, 9, 8, 8] # 11 - 19
    tens =  [3, 6, 6, 5, 5, 5, 7, 6, 6] # 10, 20, ..., 90
    if n >= 1000:
        s = spellout(n//1000) + 8
        r = n % 1000
        if r > 99:
            s = s + spellout(n%1000)
        elif r > 0:
            s = s + 3 + spellout(n%1000)
        return s
    if n > 99:
        s = spellout(n//100) + 7
        r = n % 100
        if r:
            s = s + 3 + spellout(n % 100)
        return s
    if n < 10:
        return small[n-1]
    elif n > 10 and n < 20:
        return teens[n-11]
    else:
        s = tens[n//10-1]
        if (n % 10):
            s = s + small[(n % 10) - 1]
        return s

print(sum(spellout(i) for i in range(1, 1001)))


21124

In [ ]: